#
# This file is part of Sonedyan.
# 
# Sonedyan is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation;
# either version 3 of the License, or (at your option) any
# later version.
#
# Sonedyan is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied
# warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
# PURPOSE.  See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public
# License along with Octave; see the file COPYING.  If not
# see <http://www.gnu.org/licenses/>.
# 
# Copyright (C) 2009-2014 Jimmy Dubuisson <jimmy.dubuisson@gmail.com>
#

from utils import *

fa = Graph.Read_GraphML('fa-core-graphml.xml')

cvid=fa.vs(name_eq="conflict")[0].index
svids = get_successors(fa,cvid,2)
pvids = get_predecessors(fa,cvid,2)

#iids = intersection(svids,pvids)
uids = union(svids,pvids)

#inames = fa.vs[iids]["name"]
#unames = fa.vs[uids]["name"]
#dnames = fa.vs[dids]["name"]

g = fa.induced_subgraph(uids)

cvid=g.vs(name_eq="conflict")[0].index
icids = g.subcomponent(cvid, mode='in')
ocids = g.subcomponent(cvid, mode='out')
iids = intersection(icids,ocids)
inames = g.vs[iids]["name"]

g.vs['color']='#ff9900'

for n in inames:
        g.vs(name_eq=n)['color']='#00acad'

g.vs(cvid)['color'] = '#ff0000'

g.write_svg("g.svg", layout=g.layout_kamada_kawai())
g.write_gml("g.gml")
g.write_graphml("g.xml")

##########

g2 = g.induced_subgraph(iids)

cvid=g2.vs(name_eq="conflict")[0].index
g2.vs['color']='#00acad'
g2.vs(cvid)['color'] = '#ff0000'

g2.write_svg("g_b.svg", layout=g.layout_kamada_kawai())
g2.write_gml("g_b.gml")
g2.write_graphml("g_b.xml")

##########

writer = FilteredMemoryWriter(3)
c = Cycles(g2, writer, 3)

c.log.setLevel(logging.INFO)
ch = logging.StreamHandler()
#ch.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
ch.setFormatter(formatter)
c.log.addHandler(ch)

c.cycles()
c3ids = get_v3_ids(g2,writer.cycles)
e3ids = get_e3_ids(g2,writer.cycles)

nc3ids = difference(g2.vs.indices,c3ids)
ne3ids = difference(g2.es.indices,e3ids)

#for i in nc3ids:
#       g2.vs(i)['color']='#ff9900'
g2.vs(nc3ids)['color']='#ff9900'
g2.es(ne3ids)['color']='#ff9900'

g2.write_svg("g_c.svg", layout=g.layout_kamada_kawai())
g2.write_gml("g_c.gml")
g2.write_graphml("g_c.xml")

##########

g2.delete_edges(ne3ids)
zvids = g2.vs.select(_degree_eq=0).indices
c3ids = difference(c3ids,zvids)
g3 = g2.induced_subgraph(c3ids)

cvid=g3.vs(name_eq="conflict")[0].index
g3.vs['color']='#00acad'
g3.vs(cvid)['color'] = '#ff0000'
del g3.es["color"]

g3.write_svg("g_d.svg", layout=g.layout_kamada_kawai())
g3.write_gml("g_d.gml")
g3.write_graphml("g_d.xml")

##########
